﻿using LPBToolsLib;
using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FileRenameToolsV2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public FNViewModel FileNameView { get; }=new FNViewModel();
        
        public MainWindow()
        {
            InitializeComponent();
            FileNameView.SourFiles.Clear();
            sourFilesDatasGridList.ItemsSource = FileNameView.SourFiles;
            destFilesDatasGridList.ItemsSource = FileNameView.DestFiles;
            numberUnDownStar.ValueChanged += textbox目标文件名称_LostFocus;
            // 设置数据上下文为视图模型（所有绑定的根）
            //DataContext = FileNameView;
            FileNameView.SourFilesView.CollectionChanged += SourFilesView_CollectionChanged;
        }

        /// <summary>
        /// 排序事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SourFilesView_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            ICollectionView view = (ICollectionView)sender;
            string sFileColumnCName = DisplayNameHelper.GetDisplayName(typeof(TFileInfo), "FileName");
            // 情况1：无排序（用户取消排序或初始状态）
            if (view.SortDescriptions.Count == 0)
            {
                SourFileGrid_FileColumn.Header = sFileColumnCName;
                return;
            }

            // 情况2：有排序（获取当前排序字段和方向）
            SortDescription currentSort = view.SortDescriptions[0];
            string currentField = currentSort.PropertyName;
            if (currentField.Equals("FileName"))
            {
                if (currentSort.Direction == ListSortDirection.Descending)
                    SourFileGrid_FileColumn.Header = sFileColumnCName+" ↑";
                else
                    SourFileGrid_FileColumn.Header = sFileColumnCName+" ↓";
            }
        }

        private void SourFileGrid_Drop(object sender, DragEventArgs e)
        {
            if ((e.Effects & DragDropEffects.Copy)!=0)
            {
                // 获取拖拽的文件路径数组
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (files != null && files.Length > 0)
                {
                    foreach (string file in files)
                    {
                        string sNameEx = System.IO.Path.GetFileName(file);
                        string sName = System.IO.Path.GetFileNameWithoutExtension(file);
                        string sExtN = "";
                        if (!string.IsNullOrEmpty(sName))
                            sExtN=sNameEx.Replace(sName, string.Empty);
                        else
                            sExtN= sNameEx;
                            //string sDir=Path.GetDirectoryName(file);
                            TFileInfo tFileInfo = new TFileInfo { FileName = sName, ExtName = sExtN, FileNDirects = file };
                        if (!FileNameView.isExists(FileNameView.SourFiles, tFileInfo))
                        {
                            FileNameView.SourFiles.Add(tFileInfo);
                        }
                    }
                }
            }
            if ((e.Effects & DragDropEffects.Move) != 0)
            {
                var targetRow = sender as DataGridRow;
                var targetItem = targetRow?.Item as TFileInfo;

                if (_draggedItem != null && targetItem != null && !_draggedItem.Equals(targetItem))
                {
                    FileNameView.SourFilesView.SortDescriptions.Clear();
                    TFileInfo tSourItem = _draggedItem;
                    _draggedItem = null;


                    int originalIndex = FileNameView.SourFiles.IndexOf(tSourItem);
                    int targetIndex = FileNameView.SourFiles.IndexOf(targetItem);

                    // 移除原始项
                    FileNameView.SourFiles.RemoveAt(originalIndex);

                    // 插入到目标位置
                    if (originalIndex < targetIndex)
                    {
                        // 如果从上方拖到下方，目标索引需要减1
                        FileNameView.SourFiles.Insert(targetIndex, tSourItem);
                    }
                    else
                    {
                        FileNameView.SourFiles.Insert(targetIndex, tSourItem);
                    }

                    // 重新选中移动后的行
                    sourFilesDatasGridList.SelectedItem = tSourItem;
                    sourFilesDatasGridList.ScrollIntoView(tSourItem);                    
                }

                e.Handled = true;
                _draggedItem = null;  // 重置拖拽对象
            }
        }

        private void SourFileGrid_DragOver(object sender, DragEventArgs e)
        {
            // 检查拖拽的数据是否包含文件
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // 允许拖拽操作
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                var targetRow = sender as DataGridRow;
                var targetItem = targetRow?.Item as TFileInfo;
                var draggedItem = e.Data.GetData(typeof(TFileInfo)) as TFileInfo;
                DragTargetItemName.Text = targetItem?.FileName;
                DragSourItemName.Text = draggedItem?.FileName;
                if (draggedItem != null && targetItem != null && !draggedItem.Equals(targetItem))
                {
                    e.Effects = DragDropEffects.Move;
                }
                else
                {
                    if (draggedItem != null && targetItem != null)
                        e.Effects = DragDropEffects.None;
                    else
                    if(draggedItem == null || targetItem == null)
                        e.Effects = DragDropEffects.None;
                    e.Effects = DragDropEffects.None;
                }
            }
            e.Handled = true;
        }

        private TFileInfo? _draggedItem;
        private bool _isDragging;
        private Point _dragStartPoint;

        // 检测鼠标移动，开始拖拽
        private void DataGridRow_MouseMove(object sender, MouseEventArgs e)
        {
            if (_draggedItem == null) return;

            // 计算鼠标
            var mousePos = e.GetPosition(null);
            var dragDelta = _dragStartPoint - mousePos;

            // 当鼠标移动距离
            if (e.LeftButton == MouseButtonState.Pressed &&
                (Math.Abs(dragDelta.X) > SystemParameters.MinimumHorizontalDragDistance ||
                 Math.Abs(dragDelta.Y) > SystemParameters.MinimumVerticalDragDistance))
            {
                _isDragging = true;
                // 开始拖拽
                DragDrop.DoDragDrop(sender as DependencyObject, _draggedItem, DragDropEffects.Move);
                _isDragging = false;
                _draggedItem = null;
            }
        }

        private void sourFilesList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 1. 获取鼠标点击位置对应的元素
            var hitTestResult = VisualTreeHelper.HitTest(sourFilesDatasGridList, e.GetPosition(sourFilesDatasGridList));
            if (hitTestResult?.VisualHit == null)
                return;

            // 2. 从点击元素向上查找对应的DataGridRow（记录行）
            var targetRow = FindVisualParent<DataGridRow>(hitTestResult.VisualHit);
            if (targetRow == null)
                return; // 未点击到记录行（如标题栏、空白区域）

            // 3. 获取行对应的数据源记录
            var targetItem = targetRow.Item;
            if (targetItem == null)
                return;
            // 清除现有选中，设置新选中项
            sourFilesDatasGridList.SelectedItem = targetItem;
            // 确保行获得焦点（可选）
            targetRow.Focus();
            _draggedItem = (TFileInfo)targetItem;
            _dragStartPoint = e.GetPosition(null);
        }

        // 辅助方法：从视觉树中向上查找指定类型的父元素
        private T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            while (child != null)
            {
                if (child is T parent)
                    return parent;
                // 向上查找父级元素
                child = VisualTreeHelper.GetParent(child);
            }
            return null;
        }

        private void textbox目标目录_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            OpenFolderDialog tOpenFloder = new OpenFolderDialog();
            tOpenFloder.Title = "选择目录";
            tOpenFloder.Multiselect = false;       

            if (!string.IsNullOrEmpty(textbox目标目录.Text))
                tOpenFloder.InitialDirectory = textbox目标目录.Text;
            if (tOpenFloder.ShowDialog()==true)
                textbox目标目录.Text = tOpenFloder.FolderName;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void textbox目标文件名称_LostFocus(object sender, RoutedEventArgs e)
        {
            getFileNameList();
        }

        private string ExtractFirstInnermostContent(string input)
        {
            // 正则表达式：匹配"内部无其他括号的括号对"（即最内侧括号）
            // \(: 匹配左括号（转义处理）
            // ([^()]*): 捕获组，匹配"除小括号外的任意字符"（确保内部无嵌套）
            // \): 匹配右括号（转义处理）
            Regex regex = new Regex(@"\(([^()]*)\)");

            // 获取所有最内侧括号的匹配结果
            MatchCollection matches = regex.Matches(input);

            // 若有匹配结果，返回第一个匹配的括号内内容；否则返回空
            return matches.Count > 0 ? matches[0].Groups[1].Value : string.Empty;
        }

        private bool getFileNameList()
        {
            string sRNMask = textbox目标文件名称.Text;
            string sFlowerMask = ExtractFirstInnermostContent(sRNMask);
            if ((!string.IsNullOrEmpty(sRNMask)) && (!string.IsNullOrEmpty(sFlowerMask))
                && (FileNameView.SourFiles.Count > 0))
            {
                FileNameView.DestFiles.Clear();
                int iFlow = numberUnDownStar.Value;
                foreach (TFileInfo item in FileNameView.SourFiles)
                {
                    string sTmp1 = iFlow.ToString();
                    //string sTmp2 = sTmp1;
                    if (sTmp1.Length < sFlowerMask.Length)
                    {
                        sTmp1 = "00000000000" + sTmp1;

                        if (sTmp1.Length > sFlowerMask.Length)
                            sTmp1 = sTmp1.Substring(sTmp1.Length - sFlowerMask.Length, sFlowerMask.Length);
                    }
                    string sDestFN = sRNMask.Replace($"({sFlowerMask})", sTmp1) + item.ExtName;
                    string sDestFNDir = textbox目标目录.Text + "\\" + sDestFN;
                    FileNameView.DestFiles.Add(new TFileInfo { FileName = sDestFN, ExtName = item.ExtName, FileNDirects = sDestFNDir });
                    iFlow++;
                }
                return true;
            }
            return false;
        }

        private void textbox目标文件名称_TextChanged(object sender, TextChangedEventArgs e)
        {
            getFileNameList();
        }
    }
}